<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

// 检查IP是否被封禁
$user_ip = get_user_ip();
if (is_ip_banned($user_ip)) {
    die("<div style='text-align: center; margin-top: 50px;'><h1>您的IP已被封禁，无法访问本站</h1></div>");
}

// 确定发布类型
$post_type = isset($_GET['type']) ? $_GET['type'] : 'confession';
if (!in_array($post_type, ['confession', 'daily'])) {
    $post_type = 'confession';
}

$message = '';
$message_type = '';

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 验证内容
    if ($post_type === 'confession') {
        $confessor = trim($_POST['confessor'] ?? '');
        $is_anonymous = isset($_POST['anonymous']) ? 1 : 0;
        $target_person = trim($_POST['target_person'] ?? '');
        $content = trim($_POST['content'] ?? '');
        
        if (empty($confessor) && !$is_anonymous) {
            $message = '请输入你的名字';
            $message_type = 'error';
        } elseif (empty($target_person)) {
            $message = '请输入被表白人的名字';
            $message_type = 'error';
        } elseif (empty($content)) {
            $message = '请输入表白内容';
            $message_type = 'error';
        } elseif (has_prohibited_words($content) || has_prohibited_words($confessor) || has_prohibited_words($target_person)) {
            $message = '内容包含违禁词，请修改后重新提交';
            $message_type = 'error';
        } else {
            // 处理图片上传
            $image_url = '';
            if (!empty($_FILES['image']['name'])) {
                $upload_result = upload_image($_FILES['image']);
                if (!$upload_result['success']) {
                    $message = $upload_result['message'];
                    $message_type = 'error';
                } else {
                    $image_url = $upload_result['filename'];
                }
            }
            
            // 如果没有错误，保存表白内容
            if (empty($message)) {
                try {
                    $stmt = $pdo->prepare("INSERT INTO confessions (confessor, is_anonymous, target_person, content, image_url, ip_address) 
                                         VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt->execute([
                        $confessor,
                        $is_anonymous,
                        $target_person,
                        $content,
                        $image_url,
                        $user_ip
                    ]);
                    
                    $message = '表白发布成功！';
                    $message_type = 'success';
                    
                    // 清空表单
                    $confessor = $target_person = $content = '';
                    $is_anonymous = 0;
                } catch (PDOException $e) {
                    $message = '发布失败，请重试';
                    $message_type = 'error';
                }
            }
        }
    } else { // 日常
        $poster = trim($_POST['poster'] ?? '');
        $content = trim($_POST['content'] ?? '');
        
        if (empty($poster)) {
            $message = '请输入你的名字';
            $message_type = 'error';
        } elseif (empty($content)) {
            $message = '请输入日常内容';
            $message_type = 'error';
        } elseif (has_prohibited_words($content) || has_prohibited_words($poster)) {
            $message = '内容包含违禁词，请修改后重新提交';
            $message_type = 'error';
        } else {
            // 处理图片上传
            $image_url = '';
            if (!empty($_FILES['image']['name'])) {
                $upload_result = upload_image($_FILES['image']);
                if (!$upload_result['success']) {
                    $message = $upload_result['message'];
                    $message_type = 'error';
                } else {
                    $image_url = $upload_result['filename'];
                }
            }
            
            // 如果没有错误，保存日常内容
            if (empty($message)) {
                try {
                    $stmt = $pdo->prepare("INSERT INTO dailies (poster, content, image_url, ip_address) 
                                         VALUES (?, ?, ?, ?)");
                    $stmt->execute([
                        $poster,
                        $content,
                        $image_url,
                        $user_ip
                    ]);
                    
                    $message = '日常发布成功！';
                    $message_type = 'success';
                    
                    // 清空表单
                    $poster = $content = '';
                } catch (PDOException $e) {
                    $message = '发布失败，请重试';
                    $message_type = 'error';
                }
            }
        }
    }
}

// 获取音乐URL
$music_url = get_setting('music_url');
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $post_type == 'confession' ? '发布表白' : '发布日常'; ?> - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* 全局样式 */
        body {
            background-color: #fff5f8;
            color: #333;
            font-family: 'Arial', sans-serif;
            padding: 20px 0;
        }
        
        /* 樱花飘落效果 */
        .sakura {
            position: fixed;
            background-color: #ffccd5;
            border-radius: 50% 50% 30% 70%;
            pointer-events: none;
            z-index: 100;
            animation: fall linear infinite;
        }
        
        @keyframes fall {
            to {
                transform: translateY(100vh) rotate(720deg);
                opacity: 0;
            }
        }
        
        /* 容器样式 */
        .container {
            max-width: 800px;
            background-color: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
        }
        
        /* 标题样式 */
        .page-title {
            color: #ff69b4;
            text-align: center;
            margin-bottom: 30px;
            font-size: 2rem;
        }
        
        /* 表单样式 */
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            font-weight: bold;
            color: #d63384;
            margin-bottom: 8px;
            display: block;
        }
        
        .form-control {
            width: 100%;
            padding: 12px;
            border: 1px solid #ffccd5;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s;
        }
        
        .form-control:focus {
            border-color: #ff69b4;
            outline: none;
            box-shadow: 0 0 0 3px rgba(255, 105, 180, 0.2);
        }
        
        textarea.form-control {
            min-height: 150px;
            resize: vertical;
        }
        
        /* 按钮样式 */
        .btn {
            padding: 10px 20px;
            border-radius: 8px;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s;
            border: none;
        }
        
        .btn-primary {
            background-color: #ff69b4;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #d63384;
        }
        
        .btn-secondary {
            background-color: #f8d7da;
            color: #721c24;
            margin-right: 10px;
        }
        
        .btn-secondary:hover {
            background-color: #f5c6cb;
        }
        
        .btn-group {
            display: flex;
            justify-content: center;
            margin-top: 30px;
        }
        
        /* 消息提示 */
        .message {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .message-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .message-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        /* 匿名选项 */
        .anonymous-option {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .anonymous-option input {
            margin-right: 10px;
            width: auto;
        }
        
        /* 图片上传 */
        .image-upload {
            margin-bottom: 20px;
        }
        
        .image-upload input {
            border: 1px solid #ffccd5;
            padding: 8px;
            border-radius: 8px;
            width: 100%;
        }
        
        /* 返回链接 */
        .back-link {
            display: inline-block;
            margin-bottom: 20px;
            color: #ff69b4;
            text-decoration: none;
        }
        
        .back-link:hover {
            color: #d63384;
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <!-- 樱花飘落效果容器 -->
    <div id="sakura-container"></div>
    
    <!-- 音乐播放器 -->
    <?php if (!empty($music_url)): ?>
    <audio id="background-music" loop>
        <source src="<?php echo $music_url; ?>" type="audio/mpeg">
    </audio>
    <?php endif; ?>
    
    <div class="container">
        <a href="index.php?module=<?php echo $post_type; ?>" class="back-link">
            <i class="fas fa-arrow-left"></i> 返回列表
        </a>
        
        <h1 class="page-title">
            <?php echo $post_type == 'confession' ? '<i class="fas fa-heart"></i> 发布表白' : '<i class="fas fa-coffee"></i> 发布日常'; ?>
        </h1>
        
        <?php if (!empty($message)): ?>
            <div class="message message-<?php echo $message_type; ?>">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>
        
        <form method="post" enctype="multipart/form-data">
            <?php if ($post_type == 'confession'): ?>
                <div class="form-group">
                    <label class="form-label" for="confessor">你的名字</label>
                    <input type="text" class="form-control" id="confessor" name="confessor" 
                           value="<?php echo isset($confessor) ? htmlspecialchars($confessor) : ''; ?>">
                </div>
                
                <div class="anonymous-option">
                    <input type="checkbox" id="anonymous" name="anonymous" 
                           <?php echo isset($is_anonymous) && $is_anonymous ? 'checked' : ''; ?>>
                    <label for="anonymous">匿名发布</label>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="target_person">向谁表白</label>
                    <input type="text" class="form-control" id="target_person" name="target_person" 
                           value="<?php echo isset($target_person) ? htmlspecialchars($target_person) : ''; ?>">
                </div>
            <?php else: ?>
                <div class="form-group">
                    <label class="form-label" for="poster">你的名字</label>
                    <input type="text" class="form-control" id="poster" name="poster" 
                           value="<?php echo isset($poster) ? htmlspecialchars($poster) : ''; ?>">
                </div>
            <?php endif; ?>
            
            <div class="form-group">
                <label class="form-label" for="content">
                    <?php echo $post_type == 'confession' ? '想对TA说' : '分享你的日常'; ?>
                </label>
                <textarea class="form-control" id="content" name="content"><?php echo isset($content) ? htmlspecialchars($content) : ''; ?></textarea>
            </div>
            
            <div class="image-upload">
                <label class="form-label" for="image">上传图片（可选）</label>
                <input type="file" id="image" name="image" accept="image/*">
                <small style="color: #666; display: block; margin-top: 5px;">支持JPG、PNG、GIF格式，最大5MB</small>
            </div>
            
            <div class="btn-group">
                <button type="button" class="btn btn-secondary" onclick="window.location='index.php?module=<?php echo $post_type; ?>'">
                    取消
                </button>
                <button type="submit" class="btn btn-primary">
                    发布
                </button>
            </div>
        </form>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // 樱花飘落效果
        function createSakura() {
            const sakuraContainer = document.getElementById('sakura-container');
            const sakura = document.createElement('div');
            sakura.classList.add('sakura');
            
            // 随机大小
            const size = Math.random() * 10 + 5;
            sakura.style.width = `${size}px`;
            sakura.style.height = `${size}px`;
            
            // 随机位置
            sakura.style.left = `${Math.random() * 100}vw`;
            sakura.style.top = `-${size}px`;
            
            // 随机透明度
            sakura.style.opacity = Math.random() * 0.8 + 0.2;
            
            // 随机动画持续时间
            const duration = Math.random() * 10 + 10;
            sakura.style.animationDuration = `${duration}s`;
            
            // 随机旋转角度
            sakura.style.transform = `rotate(${Math.random() * 360}deg)`;
            
            sakuraContainer.appendChild(sakura);
            
            // 动画结束后移除元素
            setTimeout(() => {
                sakura.remove();
            }, duration * 1000);
        }
        
        // 定时创建樱花
        setInterval(createSakura, 300);
        
        // 页面加载时创建一批樱花
        window.onload = function() {
            for (let i = 0; i < 20; i++) {
                createSakura();
            }
            
            // 自动播放音乐
            const audio = document.getElementById('background-music');
            if (audio) {
                audio.play().catch(e => {
                    console.log('无法自动播放音乐，需要用户交互:', e);
                });
            }
            
            // 匿名选项逻辑
            const anonymousCheckbox = document.getElementById('anonymous');
            const confessorInput = document.getElementById('confessor');
            
            if (anonymousCheckbox && confessorInput) {
                // 初始状态
                if (anonymousCheckbox.checked) {
                    confessorInput.disabled = true;
                    confessorInput.placeholder = '匿名发布时无需填写';
                }
                
                // 监听复选框变化
                anonymousCheckbox.addEventListener('change', function() {
                    confessorInput.disabled = this.checked;
                    if (this.checked) {
                        confessorInput.placeholder = '匿名发布时无需填写';
                    } else {
                        confessorInput.placeholder = '';
                    }
                });
            }
        };
    </script>
</body>
</html>
